import { MongoClient } from 'mongodb';
import { DATABASE_NAME } from '$lib/config.js';
import { MONGO_STRING } from "$env/static/private";

const client = await MongoClient.connect(MONGO_STRING);
const db = client.db(DATABASE_NAME);

export async function GET({url}) {
  const type = url.searchParams.get('type');
  const filter = type ? { type } : {};
  const resources = await db.collection('resources').find(filter).toArray();

  return new Response(JSON.stringify(resources));
}

export async function POST({ request }) {
  const form = await request.json();
  await db.collection('resources').insertOne(form);

  return new Response(JSON.stringify({ message: 'Resource created' }), { status: 201 });
}